package menu

import (
	"context"
	"github.com/pkg/errors"
	"trusteva/app/rbac/model"

	"trusteva/app/rbac/internal/svc"
	"trusteva/app/rbac/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type MenuDeleteLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMenuDeleteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MenuDeleteLogic {
	return &MenuDeleteLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MenuDeleteLogic) MenuDelete(req *types.MenuDeleteRo) (resp *types.BaseRsp, err error) {
	var subMenus []model.MenuConfig
	tx := l.svcCtx.DB.WithContext(l.ctx).Where("ParentId=?", req.MenuId).
		Find(&subMenus)
	if tx.Error != nil {
		return nil, tx.Error
	}
	if tx.RowsAffected > 0 {
		return nil, errors.New("有子菜单或页面，不能删除")
	}

	err = l.svcCtx.DB.WithContext(l.ctx).Where("Id=?", req.MenuId).
		Delete(&model.MenuConfig{}).Error
	return
}
